package deepbrain.markov;

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import deepbrain.simnetwork.exception.SimNetworkException;
import deepbrain.simnetwork.loader.NetworkLoader;
import deepbrain.simnetwork.loader.xml.XmlNetworkLoader;
import deepbrain.simnetwork.network.Network;
import deepbrain.simnetwork.network.NetworkState;
import deepbrain.simnetwork.util.SimNetUtils;

public class MarkovUtility {

	/**
	 * Extract the Markov transition matrix from given causal network with
	 * mechanism setted.
	 */
	public static MarkovMatrix getMarkovMatrixFromNetwork(Network network) {
		int numOfNodes = network.getNumOfNodes();
		int numOfStates = (int)Math.pow(2, numOfNodes);
		MarkovMatrix matrix = new MarkovMatrix();
		matrix.setName("Markov Transition Matrix of Network "+network.getName());
		try {
			matrix.setMatrix(new Double[numOfStates][numOfStates]);
		} catch (SimNetworkException e) {
			e.printStackTrace();
		}
		List<NetworkState> initStates = SimNetUtils.getAllCertainNetworkStates(numOfNodes);
		for(NetworkState initState:initStates) {
			NetworkState nextState = network.nextNetworkState(initState);
			int srcIndex = initState.getIndex();
			Map<NetworkState,Double> distribution = nextState.getProbabilityDistribution();
			for(Map.Entry<NetworkState,Double> entry:distribution.entrySet()) {
				matrix.setElement(srcIndex,entry.getKey().getIndex(),entry.getValue());
			}
		}
		return matrix;
	}

}
